<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="./dictionary.js"></script>
    <script>
      class Graph {
        constructor(isDirected = false) {
          this.isDirected = isDirected
          this.vertices = []
          this.adjList = new Dictionary()
        }

        // 添加一个新顶点
        addVertex(v) {
          if (!this.vertices.includes(v)) {
            this.vertices.push(v)
            this.adjList.set(v, [])
          }
        }

        // 添加边
        addEdge(v, w) {
          if (!this.adjList.get(v)) {
            this.addVertex(v)
          }
          if (!this.adjList.get(w)) {
            this.addVertex(w)
          }
          this.adjList.get(v).push(w) // v->w
          if (!this.isDirected) {
            this.adjList.get(w).push(v) // w->v
          }
        }

        // 返回顶点列表
        getVertices() {
          return this.vertices
        }
        // 返回邻接表
        getAdjList() {
          return this.adjList
        }

        toString() {
          let s = ''
          for (let i = 0; i < this.vertices.length; i++) {
            s += `${this.vertices[i]} -> `
            const neighbors = this.adjList.get(this.vertices[i])
            for (let j = 0; j < neighbors.length; j++) {
              s += `${neighbors[j]} `
            }
            s += '\n'
          }
          return s
        }
      }

      // 代码测试
      const graph = new Graph()
      const myVertices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
      for (let i = 0; i < myVertices.length; i++) {
        graph.addVertex(myVertices[i])
      }
      graph.addEdge('A', 'B')
      graph.addEdge('A', 'C')
      graph.addEdge('A', 'D')
      graph.addEdge('C', 'D')
      graph.addEdge('C', 'G')
      graph.addEdge('D', 'G')
      graph.addEdge('D', 'H')
      graph.addEdge('B', 'E')
      graph.addEdge('B', 'F')
      graph.addEdge('E', 'I')
      console.log(graph.toString())
      console.log(graph.getVertices())
      console.log(graph.getAdjList())
    </script>
  </body>
</html>
